var num = 0;
var onlinePayType = 1;
var i = 0;
var picnum = 0;
var PicturePath1 = "";
var PicturePath2 = "";
var PicturePath3 = "";
var form;

jQuery(function () {
    layui.use(['layer', 'form'], function () {
        form = layui.form();
        init();
    });
});
function init() {
    InitParentCate();
    //点击上传商品图片
    $('#picturePathInput').on('click', function () {
        openSelectImgDiv();
    });
    $("#btn").click(next);
}
var b = false;
var supplyUserId;
var result = false;
function next() {
    var parentId = $("#parentId").val()
    var cateId = $("#cateId").val()
    var specId = $("#specId").val()
    var productName = $("#productName").val()
    var price = $("#price").val();
    var overPlusNum = $("#overPlusNum").val();
    if($("#supply").val() == ''){
        easyAlert("请输入供应商登录手机号")
        return;
    }else{
        $.ajax({
            async:false,
            url:server_url + '/rest/staff/supply.do',
            data:{phone:$("#supply").val(),ran:Math.random()},
            success:function(data){
                console.log(data)
                if(data.retCode != '0000'){
                    easyAlert(data.retMsg)
                    result = false;
                    return false;
                }
                result = true
                supplyUserId = data.data.usersId;
            }
        })
    }
    if(!result){
        return;
    }
    if (parentId == null || parentId== '') {
        easyAlert("请选择一级分类！");
        return false;
    } else if (cateId == null || cateId == '') {
        easyAlert("请选择二级分类！");
        return false;
    } else if (specId == null || specId == '') {
        easyAlert("请选择类别！");
        return false;
    } else if (productName == null || productName == '') {
        easyAlert("请选择商品名！");
        return false;
    }
    if (price == "") {
        easyAlert("请输入价格！");
        return false;
    }
    if (!isPriceNumber(price)) {
        easyAlert("格式不正确！请输入正确的价格格式！");
        return false;
    }
    if (overPlusNum == "") {
        easyAlert("请输入库存！");
        return false;
    }
    localStorage.setItem("specId", specId);
    localStorage.setItem("productName", productName);
    localStorage.setItem("price", price);
    localStorage.setItem("overPlusNum", overPlusNum);
    var imgs = $("#fileList").find("img");
    if($("#img1").attr("src") == ''
        && $("#img2").attr("src") == ''
        && $("#img3").attr("src") == '')
    {
        easyAlert("请至少上传一张图片")
        return false;
    }
    PicturePath1 = $(imgs[0]).attr("src")
    PicturePath2 = $(imgs[1]).attr("src")
    PicturePath3 = $(imgs[2]).attr("src");
    if(PicturePath1 == '')
    {
        if (PicturePath2 != ''){
            PicturePath1 = PicturePath2;
        }else{
            PicturePath1 = PicturePath3;
        }
    }
    if(PicturePath2 == ''){
        PicturePath2 = PicturePath1;
    }
    if (PicturePath3 == ''){
        PicturePath3 = PicturePath1;
    }
    localStorage.setItem("PicturePath1", PicturePath1);
    localStorage.setItem("PicturePath2", PicturePath2);
    localStorage.setItem("PicturePath3", PicturePath3);
    if(b){
        return;
    }
    b = true;
    var jsonObj = [];
    jsonObj.push({name:"userid",value:supplyUserId});
    jsonObj.push({name: "specId", value: specId});
    jsonObj.push({name: "productId", value: productName});
    jsonObj.push({name: "PicturePath1", value: PicturePath1});
    jsonObj.push({name: "PicturePath2", value: PicturePath2});
    jsonObj.push({name: "PicturePath3", value: PicturePath3});
    jsonObj.push({name: "price", value: price});
    jsonObj.push({name: "overPlusNum", value: overPlusNum});
    jsonObj.push({name: "addUser", value: userid});
    jsonObj.push({name: "staff1Id", value: userid});
    jsonObj.push({name: "remark", value: $("#remark").val()});

    $.ajax({
        url: server_url + '/rest/product/skuProductAdd.do?ran='+Math.random(),
        data: jsonObj,
        type:"post",
        success: function (data) {
            easyAlert("发布成功！")
            window.location.href = server_url + '/staff/index.do';
        },
        error:function(){
            easyAlert("出了点问题")
            b = false;
        }
    })
}
function InitParentCate() {
    $.ajax({
        url: server_url + '/rest/productCate/selectParentCate.do?ran='+Math.random(),
        type: 'get',
        async: false,
        success: function (data) {
            if (data.retCode == "0000") {
                for (var i = 0; i < data.data.length; i++) {
                    $("#parentId1").append("<option  value='" + data.data[i].cateId + "'>" + data.data[i].cateName + "</option>");
                }
                form.render("select")
                form.on("select(parentId)", function (data) {
                    var pro = data.value;
                    $("#parentId").val(pro);
                    sencondCateLoad();
                })
            }
            else {
                easyDialog.open({
                    container: {
                        header: '提示',
                        content: data.retMsg
                    },
                    autoClose: 2000
                });
            }
        }
    });
}

function sencondCateLoad() {
    var parentId = $("#parentId").val();
    $.ajax({
        url: server_url + '/rest/productCate/selectChildCateKv.do?cateId=' + parentId,
        data:{ran:Math.random()},
        type: 'post',
        success: function (data) {
            $("#cateId1").html("");
            if (data.retCode == "0000") {
                var html = '<option value="">请选择</option>';
                for (var i = 0; i < data.data.length; i++) {
                    html += "<option value=" + data.data[i].cateId + ">" + data.data[i].cateName + "</option>";
                }
                $(html).appendTo("#cateId1");
                form.render("select")
                form.on("select(cateId)", function (data) {
                    var pro = data.value;
                    $("#cateId").val(pro);
                    changeSpecId();
                    changeProductName();
                });
            }
            else {
                easyDialog.open({
                    container: {
                        header: '提示',
                        content: data.retMsg
                    },
                    autoClose: 2000
                });
            }
        }
    });
}

//切换子分类选择属性名称
function changeSpecId() {
    var cateId = $("#cateId").val();
    $.ajax({
        url: server_url + '/rest/product/selectByCateId.do?ran=' + Math.random(),
        type: 'post',
        data: {cateId: cateId},
        success: function (data) {
            if (data.retCode == "0000") {
                InitSpec(data);
                form.render("select")
                form.on("select(specId)", function (data) {
                    var pro = data.value;
                    $("#specId").val(pro);
                })
            }
            else {
                easyDialog.open({
                    container: {
                        header: '提示',
                        content: data.retMsg
                    },
                    autoClose: 2000
                });
            }
        }
    });
}

//输出Dom
function InitSpec(data) {
    var html = '<option value="">请选择</option>';
    for (var i = 0; i < data.data.length; i++) {
        //if (data.data[i].specName == "类别") {
            html += "<option value=" + data.data[i].specValueId + ">" + data.data[i].specValueName + "</option>";
        //}
    }
    $("#specId1").html(html);
}

//切换子级分类
function changeProductName() {
    var parentId = $("#cateId").val();
    $.ajax({
        url: server_url + '/rest/product/getProductNameByCateId.do?ran=' + Math.random() + '&cateId=' + parentId,
        contentType: 'application/json',
        type: 'get',
        async: false,
        success: function (data) {
            $("#productName1").html('<option value="">请选择</option>');
            if (data.retCode == "0000") {
                if (data.data.nameList.length > 0) {
                    var html = '<option value="">请选择</option>';
                    for (var i = 0; i < data.data.nameList.length; i++) {
                        html += "<option value=" + data.data.nameList[i].productId + ">" + data.data.nameList[i].productName + "</option>";
                    }
                    $("#productName1").html(html);
                    form.render("select")
                    form.on("select(productName)", function (data) {
                        var pro = data.value;
                        $("#productName").val(pro);
                    });
                } else {
                    easyAlert("该分类没有商品！");
                }

            }
            else {
                easyDialog.open({
                    container: {
                        header: '提示',
                        content: data.retMsg
                    },
                    autoClose: 2000
                });
            }
        }
    });
}

function photoFile(path, i) {
    if (document.getElementById('divId').children.length < 3) {
        if (i += 1) {
            $("#picturePathInput").parent("span").next().append('<em id="emId' + i + '" class="spanC" onclick="del(' + i + ');"><input type="hidden" name="picturePath1Input' + i + '" id="picturePathInput' + i + '"><img id="picturePath' + i + '" src="" class="numImg1"><img class="clo" id="photo' + i + '"/></em>');
            if (jQuery("#picturePath" + i + "").attr("src") == "") {
                jQuery("#picturePathInput" + i + "").val(path);
                jQuery("#picturePath" + i + "").attr("src", path);
                document.getElementById("picturePath" + i + "").getAttribute("src");
                jQuery("#photo" + i + "").attr("src", "img/close2.png");
            }
        }
    } else {
        easyAlert("最多增加三张照片！");
    }
    cancelSelectImgDiv();
};
//删除
function del(a) {
    $("#photo" + a + "").attr("src", "");
    $('#emId' + a + '').remove();
    if ((undefined == $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined == $("#emId3").attr("class")) || (undefined == $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined != $("#emId3").attr("class"))) {
        i = 0;
    } else if (undefined != $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined == $("#emId3").attr("class")) {
        i = 1;
    } else if (undefined == $("#emId1").attr("class") && undefined != $("#emId2").attr("class") && undefined == $("#emId3").attr("class")) {
        $("#divId").children().attr("id", "emId1");
        $("#divId").children().attr("onclick", "del(1)");
        $("#divId").children().find("input").attr("name", "picturePath1Input1");
        $("#divId").children().find("input").attr("id", "picturePath1Input1");
        $("#divId").children().find("img").eq(0).attr("id", "picturePath1");
        $("#divId").children().find("img").eq(1).attr("id", "photo1");
        i = 1;
    } else {
        i = a - 1;
    }

    picnum--;
    if (picnum < 3) {
        $('#picturePathInput').css("display", "block");
    }

};
function toSkuProductList() {
    window.location.href = "index.do?ran=" + Math.random();
};

var onOff = true;
/*上传图片开始*/
//取消
function cancelSelectImgDiv() {

    $(".moskImg").css("display", "none");
    $(".selecImg").css({
        "display": "block",
        bottom: '-2.92rem',
        animation: '0.5s move1'
    });
    setTimeout(function () {
        $("#selecImg").css({
            display: 'none'
        })
    }, 500);
}

//打开选择窗
function openSelectImgDiv() {
    if (picnum >= 3) {
        easyAlert("最多上传三张照片！");
        return;
    }
    $(".moskImg").css({
        display: 'block'
    });
    $("#selecImg").css({
        display: "block",
        bottom: '0rem',
        animation: '0.5s move'
    });
}

//调用摄像头
function takePhoto() {
    window.photo.openCamera();
}

//调用相册
function chooseAlbum() {
    window.photo.openCamera1();
}

//获取返回路径
function getPicture(path) {

    var s = replaceAll(path, '//', '/');
    s = replaceAll(s, '"', '');
    photoFile(s, i);
    i++;
    picnum++;
}

//获取返回路径
function getPicture1(path) {
    var s = replaceAll(path, '//', '/');
    s = replaceAll(s, '"', '');
    photoFile(s, i);
    i++;
    picnum++;
    //alert(path);
}

//字符串替换
function replaceAll(s, s1, s2) {
    while (s.indexOf(s1) >= 0) {
        s = s.replace(s1, s2);
    }
    return s;
};


